package utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileManager {

    public static boolean isValidPath(String path) {
        Path p = Paths.get(path);
        return p.getFileName().toString().matches("[a-zA-Z0-9_.]+");
    }

    public static String loadFile(String path) {
        try {
            Path p = Paths.get(path);
            if (!Files.exists(p)) {
                Files.createFile(p);
                System.out.println("New file " + p + " has been created.");
                return "";  // 如果文件是新建的，返回空字符串。
            }
            return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void saveFile(String path, String content) {
        try {
            Path p = Paths.get(path);
            Files.write(p, content.getBytes(StandardCharsets.UTF_8));
            System.out.println("File saved successfully to " + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
